%% @author wenqi_zheng
%% @doc @todo Add description to socket_client.


-module(socket_client).

%% ====================================================================
%% API functions
%% ====================================================================
-export([nano_client_eval/1, startPar/1, nano_client_timeout/0]).

nano_client_eval(Str)->
	{ok, Socket} = gen_tcp:connect("localhost", 2345, [binary, {packet, 4}]),
	ok = gen_tcp:send(Socket, term_to_binary(Str)),
	
	receive
		{tcp, Socket, Bin} ->
			io:format("Client received binary = ~p~n",	[Bin]),
			Val = binary_to_term(Bin),
			io:format("Client result = ~p~n", [Val]),
			gen_tcp:close(Socket)	
	end.


nano_client_timeout()->
	{ok, Socket} = gen_tcp:connect("localhost", 2345, [binary, {active,false},
													   {send_timeout,5000},
													   {packet,4}]),	
	Parent = self(),	
	spawn(fun() -> loop1(Parent) end),	
	loop(Socket).

loop1(Parent) ->	
	Parent! {self(), send_data, term_to_binary("list_to_tuple([20, 30])") },
	receive
		Any ->		
			io:format("Recive ~p~n", [Any]),
			loop1(Parent)
	end.


loop(Sock) ->	
	receive
		{Client, send_data, Binary} ->
			io:format("Send Data ~p~n", [Binary]),
			case gen_tcp:send(Sock, [Binary]) of
				{error, timeout} ->
					io:format("Sendtimeout, closing!~n", []),
					%handle_send_timeout(),% Not implemented here
					Client! {self(),{error_sending, timeout}},
					%%Usually, it's a good idea to give up in case of a
					%%send timeout, as you never know how much actually
					%%reached the server, maybe only a packet header?!
					gen_tcp:close(Sock);
				{error, OtherSendError} ->
					io:format("Someother error on socket (~p), closing",
							  [OtherSendError]),
					Client! {self(),{error_sending, OtherSendError}},
					gen_tcp:close(Sock);
				ok->
					io:format("send OK!~n", []),
					Client! {self(), data_sent},
					loop(Sock)
			end
	end.




startPar(Number)->
	spawn(fun() -> startClient(Number) end).
	%%startClient(Number).


startClient(Number) -> 
	Pids = lib_misc:for(1, Number, 
				 fun(_Index) -> 
						 spawn(fun() -> 
									   nano_client_eval("list_to_tuple([20, 30])") 
							   end) 
				 end),
	io:format("Start Process ~p~n", [Pids]).	
	
	

%% ====================================================================
%% Internal functions
%% ====================================================================


